package com.xju.controller;

import com.xju.dao.OrderDao;
import com.xju.entity.CartItem;
import com.xju.entity.Order;
import com.xju.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/CheckoutServlet")
public class CheckoutServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        if (user == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        CartDao cartDao = new CartDao();
        List<CartItem> cartItems = cartDao.getCartItemsByUserId(user.getId());

        double totalPrice = 0;
        for (CartItem item : cartItems) {
            totalPrice += item.getProduct().getPrice() * item.getQuantity();
        }

        Order order = new Order();
        order.setUser_id(user.getId());
        order.setOrder_date(new java.util.Date()); // 当前日期时间
        order.setTotal_price(totalPrice);
        order.setStatus("待支付"); // 初始状态为待支付

        OrderDao orderDao = new OrderDao();
        orderDao.insertOrder(order);

        // 清空购物车
        orderDao.clearCartItems(user.getId());

        // 将订单信息存储在session中，以便后续页面显示
        session.setAttribute("order", order);

        // 跳转到订单确认页面
        response.sendRedirect("orderConfirmation.jsp");
    }
}
